package com.tungse.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.LongAdder;

/**
 * 信号灯
 */
public class Semaphore_Demo {
    LongAdder longAdder = new LongAdder();
    public static void main(String[] args) {
        //Semaphore 信号量
        Semaphore semaphore = new Semaphore(1);
        test01(semaphore);

    }

    private static void test01(Semaphore semaphore) {
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName()+"离开了车位");

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
